// 引入公共组件
require('../less/commCss/basic.css')
// 引入当前对应css
require('../less/register.less')
// 引入验证码插件
const Captcha = require('../lib/captcha/captcha-mini.js')
// 引入http模块,ajax请求
const {$http} = require('../lib/commonJs/http.js')
// 
const utils = require('../lib/commonJs/utils.js')

// 获取元素
const registerBtn = document.querySelector('.register-btn')
const user = document.querySelector('#user')
const verificationCode = document.querySelector('#verification-code')
const password = document.querySelector('#password')
const checkpassword = document.querySelector('#checkpassword')
const errorMsg = document.querySelector('.error-msg')

// 验证码
let catchaCode;

// 原生ajax
const ajax = new XMLHttpRequest()



// 格式化错误信息
errorMsg.textContent = ''
// 提交
registerBtn.addEventListener('click', function () {
    if (user.value == '') {
        errorMsg.textContent = '请输入账号'
    } else if (verificationCode.value != catchaCode) {
        errorMsg.textContent = '验证码错误'
    } else if (password.value == '') {
        errorMsg.textContent = '请输入密码'
    } else if (password.value != checkpassword.value) {
        errorMsg.textContent = '两次密码不一致'
    } else {
        // 无误就删除提示信息
        errorMsg.textContent = ''
        // 发送请求
        // ajax.open('post', 'http://139.9.177.51:8099/users/add')
        // ajax.onreadystatechange = function () {
        //     if (ajax.readyState == 4 && ajax.status == 200) {
        //         if (!JSON.parse(ajax.responseText).status) {
        //             alert('注册成功')
        //             location.href = './login.html'
        //         } else {
        //             alert('注册失败')
        //         }
        //     }
        // }
        // ajax.setRequestHeader('Content-Type', 'application/json')
        // ajax.send(JSON.stringify({
        //     account: user.value,
        //     password: password.value
        // }))

        // http模块ajax请求
        $http.post('/users/add', {
            account: user.value,
            password: password.value
        }, function (res) {
            if (!res.status) {
                utils.toast('success','注册成功')
                setTimeout(()=>location.href = './login.html',2000)
            } else {
                utils.toast('fail','注册失败')
            }
        })
    }
})

// 验证码
const catcha1 = new Captcha()
catcha1.draw(document.querySelector('#captcha1'), r => {
    catchaCode = r
})